<template>
	<view class="container">
		<!-- 页面导航栏 -->
		<page-navbar title="确认订单"></page-navbar>

		<!-- 收货地址 -->
		<view class="address-section" @click="goToAddressManager">
			<view class="address-header">
				<uni-icons type="location" size="18" color="#56ab2f"></uni-icons>
				<text class="address-title">收货地址</text>
				<uni-icons type="right" size="14" color="#999"></uni-icons>
			</view>
			<view class="address-content" v-if="selectedAddress.id">
				<view class="address-info">
					<text class="recipient-name">{{ selectedAddress.name }}</text>
					<text class="recipient-phone">{{ selectedAddress.phone }}</text>
				</view>
				<text class="address-detail">{{ selectedAddress.province + selectedAddress.city +
					selectedAddress.district + selectedAddress.address }}</text>
			</view>
			<view class="no-address" v-else>
				<text class="no-address-text">请选择收货地址</text>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="product-section">
			<view class="product-item">
				<image class="product-image" :src="common.defaultImg(productInfo.commodity_images)" mode="aspectFill"
					@error="handleImageError">
				</image>
				<view class="product-details">
					<view class="product-header">
						<text class="product-name">{{ productInfo.commodity_name }}</text>
						<view class="product-type">
							<text class="type-text">{{ productInfo.type?.name }}</text>
						</view>
					</view>
					<view class="product-price-section">
						<view class="product-price">
							<text class="current-price">¥{{ productPrice.toFixed(2) }}</text>
							<text class="original-price" v-if="productInfo.discount">¥{{ productInfo.sale_price
							}}</text>
						</view>
						<!-- 库存信息 -->
						<view class="stock-section">
							<text class="stock-label">库存</text>
							<text class="stock-value" :class="{ 'low-stock': productInfo.stock_quantity <= 10 }">
								{{ productInfo.stock_quantity }}
							</text>
							件
						</view>
					</view>
				</view>
			</view>



			<!-- 数量选择 -->
			<view class="quantity-section">
				<text class="quantity-label">购买数量</text>
				<view class="quantity-control">
					<view class="quantity-btn" :class="{ disabled: quantity <= 1 }" @click="decreaseQuantity">
						<uni-icons type="minus" size="16" color="#666"></uni-icons>
					</view>
					<input class="quantity-input" type="number" v-model="quantity" @input="onQuantityInput" />
					<view class="quantity-btn" :class="{ disabled: quantity >= productInfo.stock_quantity }"
						@click="increaseQuantity">
						<uni-icons type="plus" size="16" color="#666"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 优惠活动 -->
		<view class="promotion-section">
			<view class="promotion-header">
				<uni-icons type="gift" size="16" color="#FF6B6B"></uni-icons>
				<text class="promotion-title">优惠活动</text>
			</view>
			<view class="promotion-item">
				<text class="promotion-tag">满减</text>
				<text class="promotion-desc">每满200减10（可叠加）</text>
				<text class="promotion-discount" v-if="minus_amount > 0">-¥{{ minus_amount }}</text>
			</view>
			<view class="promotion-tips" v-if="productTotal >= 200">
				<text class="tips-text">
					已享受{{ Math.floor(productTotal / 200) }}次满减优惠
				</text>
			</view>
			<view class="promotion-tips" v-else-if="productTotal > 0">
				<text class="tips-text">
					还差¥{{ (200 - productTotal).toFixed(2) }}即可享受首次满减优惠
				</text>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-section">
			<view class="payment-header">
				<uni-icons type="wallet" size="18" color="#56ab2f"></uni-icons>
				<text class="payment-title">支付方式</text>
			</view>
			<view class="payment-methods">
				<view class="payment-item" :class="{ active: selectedPayment === method.value }"
					v-for="(method, index) in paymentMethods" :key="index" @click="selectPayment(method.value)">
					<view class="payment-info">
						<uni-icons :type="method.icon" size="20" :color="method.color"></uni-icons>
						<text class="payment-name">{{ method.name }}</text>
					</view>
					<view class="payment-radio">
						<view class="radio-btn" :class="{ checked: selectedPayment === method.value }"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 费用明细 -->
		<view class="cost-section">
			<view class="cost-item">
				<text class="cost-label">商品金额</text>
				<text class="cost-value">¥{{ productTotal.toFixed(2) }}</text>
			</view>
			<view class="cost-item" v-if="minus_amount > 0">
				<text class="cost-label">优惠减免</text>
				<text class="cost-value discount">-¥{{ minus_amount }}</text>
			</view>
			<view class="cost-item">
				<text class="cost-label">运费</text>
				<text class="cost-value">免运费</text>
			</view>
		</view>

		<!-- 底部支付区域 -->
		<view class="bottom-bar">
			<view class="total-info">
				<text class="total-label">实付款：</text>
				<text class="total-amount">¥{{ totalAmount }}</text>
			</view>
			<view class="pay-btn" @click="handlePay">
				<text class="pay-text">立即支付</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, toRefs } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import PageNavbar from '@/components/page-navbar/page-navbar.vue';
import SvgIcon from '@/components/svg-icon/svg-icon.vue';
import common from '@/utils/common.js';
import api from "@/api"

import useSelectStore from '@/stores/select';
const selectStore = useSelectStore();
const { selectedAddress } = toRefs(selectStore);

// 商品ID
const productId = ref('');
const quantity = ref(1);
const selectedPayment = ref('2');

// 商品信息
const productInfo = ref({});

// 支付方式
const paymentMethods = ref([
	{
		name: '微信支付',
		value: '2',
		icon: 'weixin',
		color: '#09BB07'
	},
	{
		name: '支付宝',
		value: '3',
		icon: 'wallet',
		color: '#1296DB'
	},
	{
		name: '银行卡',
		value: '1',
		icon: 'wallet',
		color: '#007AFF'
	}
]);

// 页面加载
onLoad((options) => {
	if (options.id) {
		productId.value = options.id;
	}
});

onMounted(() => {
	getData()
})

const getData = () => {
	api.commerceApi.list({
		id: productId.value,
		loding: true
	}).then((res) => {
		productInfo.value = res.list[0];
	});

	api.commerceApi.addressList({
		loding: true
	}).then((res) => {
		let result = res.list.find(item => item.id === selectedAddress.value.id)
		let defaultAddress = res.list.find(item => item.is_default == 2)
		if (!result) {
			selectedAddress.value = defaultAddress;
		}
	});
}

const productPrice = ref(0) //商品单价
const total_amount = ref(0) //订单总金额
const discount_amount = ref(0) //折扣优惠金额
const minus_amount = ref(0) //满减优惠金额
const productTotal = ref(0) //商品折扣售价

// 商品实际付款金额
const totalAmount = computed(() => {
	// 商品单价
	if (productInfo.value.discount) {
		productPrice.value = (productInfo.value.sale_price * productInfo.value.discount) || 0
	} else {
		productPrice.value = productInfo.value.sale_price || 0
	}
	// 订单总金额
	total_amount.value = productInfo.value.sale_price * quantity.value

	// 商品折扣售价
	if (productInfo.value.full_amount) {
		productTotal.value = (productInfo.value.sale_price * productInfo.value.discount) * quantity.value
	} else {
		productTotal.value = total_amount.value
	}

	// 折扣优惠金额
	discount_amount.value = total_amount.value - productTotal.value


	// 满减优惠计算（无限叠加：每满200减10）
	let actual_amount = productTotal.value

	// 计算可以享受几次满减优惠
	if (productTotal.value >= 200) {
		const fullReductionTimes = Math.floor(productTotal.value / 200)
		minus_amount.value = fullReductionTimes * 10
		actual_amount = productTotal.value - minus_amount.value
	} else {
		minus_amount.value = 0
	}

	return actual_amount.toFixed(2)
});

// 减少数量
const decreaseQuantity = () => {
	if (quantity.value > 1) {
		quantity.value--;
	}
};

// 增加数量
const increaseQuantity = () => {
	if (quantity.value < productInfo.value.stock_quantity) {
		quantity.value++;
	} else {
		uni.showToast({
			title: '库存不足',
			icon: 'none'
		});
	}
};

// 数量输入处理
const onQuantityInput = (e) => {
	const value = parseInt(e.detail.value) || 1;
	if (value > productInfo.value.stock_quantity) {
		uni.showToast({
			title: `最多只能购买${productInfo.value.stock_quantity}件`,
			icon: 'none'
		});
		setTimeout(() => {
			quantity.value = productInfo.value.stock_quantity;
		}, 500);
	} else {
		quantity.value = Math.max(1, value);
	}
};

// 选择支付方式
const selectPayment = (method) => {
	selectedPayment.value = method;
};

// 跳转地址管理
const goToAddressManager = () => {
	uni.navigateTo({
		url: '/pages/commerce/address?from=purchase'
	});
};

// 立即支付
const handlePay = () => {
	if (!selectedAddress.value.id) {
		uni.showToast({
			title: '请选择收货地址',
			icon: 'none'
		});
		return;
	}

	if (quantity.value > productInfo.value.stock_quantity) {
		uni.showToast({
			title: '库存不足',
			icon: 'none'
		});
		return;
	}

	const paymentName = paymentMethods.value.find(m => m.value === selectedPayment.value)?.name || '未知支付方式';

	uni.showModal({
		title: '确认支付',
		content: `使用${paymentName}支付 ¥${totalAmount.value} 吗？`,
		success: (res) => {
			if (res.confirm) {
				// 模拟支付处理
				uni.showLoading({
					title: '支付中...'
				});

				let customer_address = selectedAddress.value.province + selectedAddress.value.city + selectedAddress.value.district + selectedAddress.value.address
				api.commerceApi.placeOrder({
					merchant_id: 1,
					customer_name: selectedAddress.value.name,
					customer_phone: selectedAddress.value.phone,
					customer_address: customer_address,
					order_source: 1, //1-线上下单，2-现场订单
					total_amount: total_amount.value, //订单总金额
					discount_amount: total_amount.value, //折扣金额
					minus_amount: minus_amount.value, //优惠金额
					actual_amount: totalAmount.value, //实际支付金额
					payment_method: selectedPayment.value, //支付方式 1-银行转账,2-微信支付,3-支付宝支付,4-现金,5-其他付款方式
					commodity: {
						id: productInfo.value.id,
						quantity: quantity.value,
					}
				}).then((res) => {
					uni.hideLoading();

					// 支付完成后显示选择弹框
					uni.showModal({
						title: '支付成功',
						content: '您的订单支付完成！',
						cancelText: '返回',
						confirmText: '查看订单',
						success: (modalRes) => {
							if (modalRes.confirm) {
								// 点击查看订单 - 跳转到订单管理页面
								uni.redirectTo({
									url: '/pages/commerce/order'
								});
							} else if (modalRes.cancel) {
								// 点击返回 - 返回上一级页面
								uni.navigateBack();
							}
						}
					});
				});
			}
		}
	});
};

// 图片加载错误处理
const handleImageError = (event) => {
	console.log('图片加载失败，使用默认图片');
	event.target.src = '/static/images/default-commodity.svg';
};

</script>

<style lang="scss" scoped>
.container {
	background-color: #f2f1f6;
	min-height: 100vh;
	width: 100vw;
	padding-bottom: 120rpx;
	box-sizing: border-box;
}

.address-section {
	background: white;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.address-header {
		display: flex;
		align-items: center;
		gap: 10rpx;
		margin-bottom: 20rpx;

		.address-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
			flex: 1;
		}
	}

	.address-content {
		.address-info {
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-bottom: 10rpx;

			.recipient-name {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
			}

			.recipient-phone {
				font-size: 26rpx;
				color: #666;
			}
		}

		.address-detail {
			font-size: 26rpx;
			color: #666;
			line-height: 1.4;
		}
	}

	.no-address {
		.no-address-text {
			font-size: 26rpx;
			color: #999;
		}
	}
}

.product-section {
	background: white;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.product-item {
		display: flex;
		align-items: flex-start;
		gap: 20rpx;
		margin-bottom: 30rpx;

		.product-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 12rpx;
			flex-shrink: 0;
		}

		.product-details {
			flex: 1;

			.product-header {
				margin-bottom: 15rpx;

				.product-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
					display: block;
				}

				.product-type {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.type-text {
						font-size: 22rpx;
						color: #666;
						background: rgba(102, 102, 102, 0.1);
						padding: 4rpx 12rpx;
						border-radius: 8rpx;
					}
				}
			}

			.product-price-section {
				display: flex;
				align-items: center;
				justify-content: space-between;
				gap: 12rpx;

				.product-price {
					display: flex;
					align-items: center;
					gap: 12rpx;

					.current-price {
						font-size: 32rpx;
						color: #ff6b6b;
						font-weight: bold;
					}

					.original-price {
						font-size: 24rpx;
						color: #999;
						text-decoration: line-through;
					}
				}

				.stock-section {
					display: flex;
					align-items: center;
					gap: 8rpx;
					font-size: 24rpx;
					color: #999;

					.low-stock {
						color: #ff6b6b;
						font-weight: bold;
					}
				}
			}

		}
	}

	.quantity-section {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.quantity-label {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.quantity-control {
			display: flex;
			align-items: center;
			border: 2rpx solid #e0e0e0;
			border-radius: 8rpx;
			overflow: hidden;

			.quantity-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #f5f5f5;

				&.disabled {
					opacity: 0.5;
				}

				&:active {
					background: #e0e0e0;
				}
			}

			.quantity-input {
				width: 80rpx;
				height: 60rpx;
				text-align: center;
				font-size: 26rpx;
				border: none;
				background: white;
			}
		}
	}
}

.promotion-section {
	background: white;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
	border: 2rpx solid #ff6b6b;
	background: rgba(255, 107, 107, 0.05);

	.promotion-header {
		display: flex;
		align-items: center;
		gap: 10rpx;
		margin-bottom: 15rpx;

		.promotion-title {
			font-size: 26rpx;
			color: #ff6b6b;
			font-weight: bold;
		}
	}

	.promotion-item {
		display: flex;
		align-items: center;
		gap: 15rpx;

		.promotion-tag {
			background: #ff6b6b;
			color: white;
			font-size: 22rpx;
			padding: 4rpx 12rpx;
			border-radius: 8rpx;
		}

		.promotion-desc {
			font-size: 26rpx;
			color: #333;
			flex: 1;
		}

		.promotion-discount {
			font-size: 26rpx;
			color: #ff6b6b;
			font-weight: bold;
		}
	}

	.promotion-tips {
		margin-top: 15rpx;
		padding: 12rpx 16rpx;
		background: rgba(255, 107, 107, 0.1);
		border-radius: 8rpx;

		.tips-text {
			font-size: 24rpx;
			color: #ff6b6b;
		}
	}
}

.payment-section {
	background: white;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.payment-header {
		display: flex;
		align-items: center;
		gap: 10rpx;
		margin-bottom: 25rpx;

		.payment-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.payment-methods {
		.payment-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 25rpx 0;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			&.active {
				.payment-info {
					color: #56ab2f;
				}
			}

			.payment-info {
				display: flex;
				align-items: center;
				gap: 15rpx;

				.payment-name {
					font-size: 26rpx;
					color: #333;
				}
			}

			.payment-radio {
				.radio-btn {
					width: 32rpx;
					height: 32rpx;
					border: 2rpx solid #ddd;
					border-radius: 50%;
					position: relative;

					&.checked {
						border-color: #56ab2f;

						&::after {
							content: '';
							position: absolute;
							top: 50%;
							left: 50%;
							transform: translate(-50%, -50%);
							width: 16rpx;
							height: 16rpx;
							background: #56ab2f;
							border-radius: 50%;
						}
					}
				}
			}
		}
	}
}

.cost-section {
	background: white;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.cost-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15rpx 0;

		.cost-label {
			font-size: 26rpx;
			color: #666;
		}

		.cost-value {
			font-size: 26rpx;
			color: #333;

			&.discount {
				color: #ff6b6b;
			}
		}
	}
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: white;
	padding: 20rpx 30rpx;
	box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	z-index: 999;
	display: flex;
	align-items: center;
	gap: 30rpx;

	.total-info {
		flex: 1;

		.total-label {
			font-size: 26rpx;
			color: #666;
		}

		.total-amount {
			font-size: 36rpx;
			color: #ff6b6b;
			font-weight: bold;
		}
	}

	.pay-btn {
		background: linear-gradient(135deg, #56ab2f, #a8e6cf);
		color: white;
		padding: 16rpx 50rpx;
		border-radius: 50rpx;
		box-shadow: 0 4rpx 16rpx rgba(86, 171, 47, 0.4);
		transition: all 0.3s ease;
		letter-spacing: 4rpx;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba(86, 171, 47, 0.6);
		}

		.pay-text {
			font-size: 28rpx;
			font-weight: bold;
		}
	}
}
</style>
